﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Threading;
using System.Diagnostics;

namespace DreamShieldPublishRetriever
{
    public partial class FormDownloading : Form
    {
        public FormDownloading()
        {
            InitializeComponent();
        }

        public virtual void StartDownload(ProductXml Product, string DownloadPath)
        {
            if(String.IsNullOrEmpty(DownloadPath))
            {
                MessageBox.Show("Le chemin de téléchargement de l'application n'est pas définis","Attention",
                    MessageBoxButtons.OK,MessageBoxIcon.Warning);
            }
            else
            {
            string temp_file = Path.GetTempFileName();
            try
            {
                bool cancel_download = false;

                cancelBtn.Click += delegate
                {
                    cancel_download = true;
                };
                this.FormClosing += delegate
                {
                    cancel_download = true;
                };

                using (WebClient w_client = new WebClient())
                {
                    bool download_finished = false;

                    w_client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(w_client_DownloadProgressChanged);
                    w_client.DownloadFileCompleted += delegate
                    {
                        download_finished = true;
                    };

                    if (DownloadPath.IndexOf("://") < 0)
                    {
                        /* par défaut on choisis HTTP */
                        DownloadPath = "http://" + DownloadPath;
                    }
                    
                    w_client.DownloadFileAsync(new Uri(DownloadPath), temp_file);

                    while (!download_finished)
                    {
                        if (cancel_download)
                        {
                            try
                            {
                                w_client.CancelAsync();
                            }
                            catch { }
                            MessageBox.Show("Le téléchargement et l'installation de l'application ont été annulés",
                                "Attention", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }

                        Application.DoEvents();
                        Thread.Sleep(1);
                    }

                    cancelBtn.Enabled = false;
                    statusLb.Text = "Lancement de l'installation ...";
                    Application.DoEvents();

                    ProcessStartInfo s_info = new ProcessStartInfo();
                    s_info.FileName = temp_file;
                    s_info.UseShellExecute = false;
                    try
                    {
                        var p = Process.Start(s_info);

                        /* Exécution */
                        Hide();

                        p.WaitForExit();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(String.Format("L'exécution de l'installation a échouée : {0}", ex.Message),
                            "Attention", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
            finally
            {
                File.Delete(temp_file);
                Close();
            }
            }
        }

        void w_client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            if (this.InvokeRequired)
                this.Invoke(new MethodInvoker(delegate { w_client_DownloadProgressChanged(sender, e); }));
            else
            {
                downloadProgress.Maximum = 100;
                downloadProgress.Value = e.ProgressPercentage;

                progressLb.Text = String.Format("{0} / {1}",
                    GetFormatedSize(e.BytesReceived), GetFormatedSize(e.TotalBytesToReceive));
            }
        }

        public static string GetFormatedSize(long p)
        {
            if (p <= 0)
                return "0 octets";
            else if (p == 1)
                return "1 octet";
            else
            {
                double d_p = p;
                string unit = "octets";
                if (d_p >= 1024)
                {
                    d_p /= 1024.0;
                    unit = "Ko";
                }
                if (d_p >= 1024)
                {
                    d_p /= 1024.0;
                    unit = "Mo";
                }
                if (d_p >= 1024)
                {
                    d_p /= 1024.0;
                    unit = "Go";
                }
                if (d_p >= 1024)
                {
                    d_p /= 1024.0;
                    unit = "To";
                }

                return d_p.ToString("#.00") + " " + unit;
            }
        }
    }
}
